package cn.dhn_app.horseman_app.controller;

import cn.dhn_app.util.Idcard.AipOcr;
import cn.dhn_app.util.Idcard.Universal;
import cn.dhn_app.util.Idcard.util.Base64Util;
import cn.itcast.util.ResponseEntity;
import cn.web.web_module.util.IconPath;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;


/**
 * @Author lyy
 * @Description TODO
 * @PACKAGE_NAME: cn.dhn_app.horseman_app.controller
 * @ClassName HorsemanCredentials
 * @Date 2020/8/25 17:46
 * @DAY_NAME_FULL: 星期二
 * @Version 1.0
 **/
@Slf4j
@RestController
@RequestMapping(value = "/dhn/identify",produces = "application/json;charset=UTF-8")
public class HorsemanCredentials {


    /**
     * 功能描述: <br>
     * 〈骑手端注册身份证识别验证〉
     * @Author: lyy
     * @Date: 2020/8/26 15:13
     * @Param: [type, file, request, response]
     * @Return: cn.itcast.util.ResponseEntity
     */
    @RequestMapping(value = "/idCard")
    public ResponseEntity IdCard(@RequestParam("type") String type,
                                 @RequestParam("file")MultipartFile file,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {

        if(type.isEmpty()) return new ResponseEntity(303,"参数为空！");

        //图片路径
        String path = null;

        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request)){
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();
            while(iter.hasNext()){
                //一次遍历所有文件
                MultipartFile MyFile =multiRequest.getFile(iter.next().toString());
                if(MyFile!=null){
                    long time = new Date().getTime();
                    //服务器存储图片地址
//                    String filePath="/usr/tomcat/images/dhn/icon/papers/"+time+"/"+MyFile.getOriginalFilename();//松注释

                    String filePath= IconPath.ICONPATH +"icon/papers/"+time+"/"+MyFile.getOriginalFilename();
                    //服务器文件夹名字
//                    File files=new File("/usr/tomcat/images/dhn/icon/papers/"+time);//松注释


                    File files=new File(IconPath.ICONPATH+"icon/papers/"+time);
                    if(!files.exists()){            //如果文件夹不存在
                        files.mkdir();              //创建文件夹

                    }
                    //图片地址
                    path="https://www.dhnep.cn:8181/dhn/icon/papers/"+time+"/"+MyFile.getOriginalFilename();
                    //上传图片至服务器
                    MyFile.transferTo(new File(filePath));

                }
            }
        }

        //服务器图片地址
//        URL img = new  URL("https://www.dhnep.cn:8181/dhn/icon/papers/1598414458693/shz.jpg");
        URL img = new  URL(path);

        BufferedImage image = ImageIO.read(img);

        ByteArrayOutputStream os = new ByteArrayOutputStream();

        ImageIO.write(image, "jpg", os);

        //调用证件识别接口
        AipOcr idCard = new AipOcr(Universal.BD_APP_ID_GHJ,Universal.BD_API_Key_GHJ,Universal.BD_Secret_Key_GHJ);

        String decide = null;

        //设置证件识别配置参数
        HashMap<String, String> options = new HashMap<>();

        if(type.equals("front")) {
            decide = "front";
            log.info("该身份证照片属于正面：{}",decide);
        }else if(type.equals("back")){
            decide = "back";
            log.info("该身份证照片属于反面：{}",decide);
        }
        //front：身份证含照片的一面；back：身份证带国徽的一面
        options.put("id_card_side",decide);
        //是否检测图像旋转角度
        //- true：检测旋转角度；
        //- false：不检测旋转角度。
        options.put("detect_direction","true");

        //调用身份证识别接口
        JSONObject jsonObject = idCard.idCard(os.toByteArray(),decide,options);

        //将身份证识别接口 转成json
        com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(String.valueOf(jsonObject));

        //判断识别后返回的结果
        if(jsonObject.get("image_status").equals("reversed_side")){

            return new ResponseEntity(400,"身份证正反面颠倒！！！");

        }else if(jsonObject.get("image_status").equals("non_idcard")){

            return new ResponseEntity(401,"上传的图片中不包含身份证！！！");

        }else if(jsonObject.get("image_status").equals("other_type_card")){

            return new ResponseEntity(402,"其他类型证照！！！");

        }else if(jsonObject.get("image_status").equals("over_exposure")){

            return new ResponseEntity(403,"身份证关键字段反光或过曝！！！");

        }else if(jsonObject.get("image_status").equals("over_dark")){

            return new ResponseEntity(405,"身份证欠曝（亮度过低）！！！");

        } else if(jsonObject.get("image_status").equals("normal")){

            log.info("身份证验证通过！！！");
            return new ResponseEntity(json);

        }else {
            return new ResponseEntity().error_300();

        }
    }


    /**
     * 功能描述: <br>
     * 〈驾驶证识别接口〉
     * @Author: lyy
     * @Date: 2020/8/27 15:35
     * @Param: [file, request, response]
     * @Return: cn.itcast.util.ResponseEntity
     */
    @RequestMapping(value = "/driving")
    public ResponseEntity drivingIdentify(@RequestParam(value = "file")MultipartFile file,
                                          HttpServletRequest request,
                                          HttpServletResponse response) throws IOException {
        //图片路径
        String path = null;

        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request)){
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();
            while(iter.hasNext()){
                //一次遍历所有文件
                MultipartFile MyFile =multiRequest.getFile(iter.next().toString());
                if(MyFile!=null){
                    long time = new Date().getTime();
                    //服务器存储图片地址
//                    String filePath="/usr/tomcat/images/dhn/icon/license/"+time+"/"+MyFile.getOriginalFilename(); //松注释

                    String filePath=IconPath.ICONPATH+"icon/license/"+time+"/"+MyFile.getOriginalFilename();
                    //服务器文件夹名字
//                    File files=new File("/usr/tomcat/images/dhn/icon/license/"+time);   //松注释

                    File files=new File(IconPath.ICONPATH+"icon/license/"+time);   //松注释

                    if(!files.exists()){            //如果文件夹不存在
                        files.mkdir();              //创建文件夹
                    }
                    //图片地址
                    path="https://www.dhnep.cn:8181/dhn/icon/license/"+time+"/"+MyFile.getOriginalFilename();
                    //上传图片至服务器
                    MyFile.transferTo(new File(filePath));
                }
            }
        }


        //服务器图片地址
//        URL img = new  URL("https://www.dhnep.cn:8181/dhn/icon/papers/1598414458693/jsz.jpg");
        URL img = new  URL(path);

        BufferedImage image = ImageIO.read(img);

        ByteArrayOutputStream os = new ByteArrayOutputStream();

        ImageIO.write(image, "jpg", os);

        //调用证件识别接口
        AipOcr idCard = new AipOcr(Universal.BD_APP_ID_GHJ,Universal.BD_API_Key_GHJ,Universal.BD_Secret_Key_GHJ);

        //设置证件识别配置参数
        HashMap<String, String> options = new HashMap<>();

        //检测朝向
        options.put("detect_direction","true");
        //归一化格式输出驾驶证的「有效起始日期」+「有效期限」及「有效期限」+「至」两种输出格式归一化为「有效起始日期」+「失效日期」
        options.put("unified_valid_period","true");

        //调用身份证识别接口
        JSONObject jsonObject = idCard.drivingLicense(os.toByteArray(),options);

        //将身份证识别接口 转成json
        com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(String.valueOf(jsonObject));

        log.info("驾驶证识别数据：{}",json);

        return new ResponseEntity(json);
    }


    @RequestMapping(value = "/drivingssss")
    public ResponseEntity drivingIdentifys() throws IOException{

//        MultiFormatReader formatReader = new MultiFormatReader();

        //服务器图片地址
        URL img = new  URL("https://www.dhnep.cn:8181/dhn/二维码.jpg");

        File imgs = new File("E:/images/osdn25Ym8McrfpUo-3jVCzKS9700.jpg");

        BufferedImage image = ImageIO.read(img);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", os);
        String base64Content = Base64Util.encode(os.toByteArray());
        generateImage(base64Content, "E:\\images\\二维码.jpg");

        return new ResponseEntity();
    }

    /**
     * base64字符串转换成图片
     * @param imgStr
     * @param path
     * @return
     */
    public static boolean generateImage(String imgStr, String path) {
        if (imgStr == null)
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // 解密
            byte[] b = decoder.decodeBuffer(imgStr);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
